<!--
  使用eg:
	<el-form-item label="营业执照" prop="licenseUrl">
	  <d-upload-oss v-model="enterpriseData.licenseUrl" :list="licenseImage" :accept="['png','jpg','jpeg','bmp']" listType="picture-card" :size="102400" class="pic-upload-ctrl"
		saveType="licenseImg" saveDir="enterprise/licenseImg" @httpRequest="saveImg" @validateField="$refs['enterpriseForm'].validateField('licenseUrl')" :disabled="formDisabled">
		<div class="hint-text">上传营业执照</div>
	  </d-upload-oss>
	</el-form-item>
		
  // 存储从oss返回的图片路径
  saveImg(result, saveType) {
    if(!result.errorCode) {
      switch (saveType) {
        case 'licenseImg':
          this.enterpriseData.licenseUrl = result;
          break;
        case 'logoImg':
          this.enterpriseData.logoUrl = result;
          break;
        default:
          break;
      }
    } else {
      this.$message.error(result.errorCode || '上传失败');
    }
  },

  显示：
  (1) this.gateImgList = s.gateImg && s.gateImg != 'null' && s.gateImg != null ? [{ url: this.$util.url.fileUrl + s.gateImg }] : [];
  (2) <d-image :src="$util.url.fileUrl + gate.gateImg" width="150px" height="150px"></d-image>
-->

<template>
  <div class="d-upload-select">
    <el-upload
      ref="dUploadSelect"
      action=""
      :file-list="list"
      :multiple="multiple"
      :list-type="listType"
      :limit="limit"
      :show-file-list="showFileList"
      :before-upload="beforeUpload"
      :on-exceed="onExceed"
      :on-remove="onRemove"
      :http-request="httpRequest"
      :disabled="disabled">
      <div slot="tip" class="el-upload__tip">
        <div class="d-upload-select-explain">{{ explain }}</div>
      </div>
      <div slot="file" slot-scope="{ file }" v-if="listType === 'picture-card'">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        {{ listShowChange(file) }}
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="viewMagnifyImage(file.url)"><i class="el-icon-zoom-in"></i></span>
          <span class="el-upload-list__item-delete" v-if="!disabled" @click="removeImage(file)"><i class="el-icon-delete"></i></span>
        </span>
      </div>
      <slot></slot>
    </el-upload>
    <el-dialog title="图片" :visible.sync="magnifyImageShow">
      <div class="preview-image"><img :src="imageUrl" alt="" /></div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'd-upload-select',
  model: {
    prop: 'file',
    event: 'change'
  },
  props: {
    file: {},
	//提示信息
    explain: String,
    limit: {
      //数量
      type: Number,
      default: 1
    },
    multiple: {
      //是否多文件
      type: Boolean,
      default: false
    },
    size: {
      //大小，默认1M
      type: Number,
      default: 1024
    },
    list: {
      //默认列表
      type: Array,
      default: function() {
        return [];
      }
    },
    listType: {
      //显示类型
      type: String,
      default: 'text'
    },
    accept: {
      //上传文件类型
      type: [Array, String],
      default: function() {
        return [];
      }
    },
    showFileList: {
      //是否显示文件列表
      type: Boolean,
      default: true
    },
    listShow: {
      //是否显示文件列表，picture-card
      type: Boolean,
      default: true
    },
    disabled: {
      //是否禁用
      type: Boolean,
      default: false,
    },
    // 文件上传oss目录
    saveDir: {
      type: String,
      default: '',
    },
    // 文件返回识别字段
    saveType: {
      type: String,
      default: '',
    }
  },
  data() {
    return {
      magnifyImageShow: false,
      imageUrl: ''
    };
  },
  methods: {
    //删除文件
    onRemove: function(file, fileList) {
      if (this.multiple) {
        // this.$emit('change', fileList);
      } else {
        this.$emit('change', '');
        this.$emit('delete', this.saveType)
      }
      this.showUpload('visible');
      this.$emit('validateField');
      this.$emit('remove');
    },

    //文件上传前
    beforeUpload(file) {
      this.$emit('changeLogin', true);
      //判断上传文件类型
      var type = file.name.substring(file.name.lastIndexOf('.') + 1).toLocaleLowerCase();
      if (this.accept.indexOf(type) === -1 && this.accept.length !== 0) {
        this.message.warning(`请选择 ${this.accept.join(' / ')} 类型的文件`);
        this.$emit('changeLogin', false);
        return false;
      }

      //判断上传文件大小
      if (this.size < file.size / 1024) {
        let m = (this.size / 1024).toFixed(2);
        let size = m >= 1 ? m + 'M' : this.size + 'KB';
        this.message.warning(`文件大小不能超过 ${size}`);
        this.$emit('changeLogin', false);
        return false;
      }

      if((this.multiple && this.list.length == this.limit) || !this.multiple) {
        this.showUpload('hidden')
      }
    },

    //上传文件数量限制
    onExceed: function() {
      this.message.warning(`只能选择${this.limit}个文件`);
    },

    //删除图片
    removeImage: function(file) {
      if(this.multiple) {
        let fileList = this.$refs.dUploadSelect.uploadFiles;
        let index = 0;
        fileList.map(item => {
          if(item.uid == file.uid) {
            this.$refs.dUploadSelect.uploadFiles.splice(index, 1);
            this.$emit('delete', this.saveType, index)
            this.showUpload('visible');
            this.$emit('validateField');
          }
          index++;
        })
      } else {
        this.$refs['dUploadSelect'].handleRemove(file);
      }
    },

    //清除文件列表
    clearFiles: function() {
      this.$refs['dUploadSelect'].clearFiles();
      this.showUpload('visible')
    },

    //自定义上传文件
    async httpRequest({ file }) {
      if (this.multiple) {
        // this.file.push(file);
        this.ossUpload(file);
        this.$emit('changeLogin', false);
      } else {
        this.$emit('change', file);
        this.ossUpload(file);
        this.$emit('changeLogin', false);
        this.$emit('validateField');
      }
    },

    //上传至oss
    async ossUpload(file) {
      var result = await this.$alioss.put(file, this.saveDir);
      this.$emit('httpRequest', result, this.saveType);
    },

    //隐藏上传图片组件
    showUpload: function(value) {
      this.$refs.dUploadSelect.$el.childNodes[1].style.visibility = value;
    },

    //获取文件信息
    listShowChange: function(file) {
      return '';
    },

    //查看图片
    viewMagnifyImage: function(url) {
      // let index = url.indexOf('blob:');
      // if (index === -1) {
      //   this.imageUrl = url + '?prevType=Y';
      // } else {
      //   this.imageUrl = url;
      // }
      this.imageUrl = url;
      this.magnifyImageShow = true;
    }
  },
  watch: {
    'list.length'(n, l) {
      if (this.list.length === this.limit) {
        this.showUpload('hidden');
      }
    },
    listShow() {
      console.log(this.listShow);
    },
    'file.length'(n, l) {
      if (this.file.length === this.limit) {
        this.showUpload('hidden');
      }
    }
  }
};
</script>

<style scoped>
.el-upload__tip {
  line-height: 21px;
  margin-top: 0px;
}

.preview-image {
  text-align: center;
}

.preview-image img {
  max-width: 500px;
  max-height: 500px;
}

.d-upload-select-explain {
  font-size: 13px;
  color: #999;
  margin-top: 5px;
}

.el-upload-list__item-thumbnail {
  width: 146px;
  height: 146px;
  object-fit: contain;
}
</style>
